/**
 * alertProvider module
 */

  var consts = require("../../utils/consts");
  var alertProvider = (function (){
      var alerts = [];

      var doAlert = function (heading, message, type, sticky, duration){
          var alert = {
              heading: heading,
              message: message.replace(/\n/g, '<br/>'),
              type: type,
              sticky: sticky || false
          };

          if (!sticky){
              alert.timeout = setTimeout(function (){
                  closeByMatch(alert);
              }, duration || 3000);
          }

          if (!alerts[alerts.length - 1] || alerts[alerts.length - 1].message !== alert.message){
              alerts.push(alert);
          }

          return alert;
      };

      var closeByMatch = function (alert){
          for (var i = 0, item; item = alerts[i++];){
              if (item === alert){
                  close(i);
                  break;
              }
          }
      };

      var close = function (i){
          if (alerts[i] && alerts[i].timeout){
              clearTimeout(alerts[i].timeout);
          }
          alerts.splice(i, 1);
      };

      var closeByAlert = function (alert){
          var index = alerts.indexOf(alert);
          if (index != -1){
              alerts.splice(index, 1);
          }
      };

      var fatal = function (message){
          doAlert('', message, consts.INFO_TYPES.FATAL);
      };

      var error = function (message){
          doAlert('', message, consts.INFO_TYPES.ERROR, false, 5000);
      };

      var warning = function (message){
          doAlert('', message, consts.INFO_TYPES.WARNING);
      };

      var info = function (message, isSticky){
          return doAlert('', message, consts.INFO_TYPES.INFO, isSticky);
      };

      var success = function (message){
          doAlert('', message, consts.INFO_TYPES.SUCCESS);
      };

      return {
          info: info,
          error: error,
          fatal: fatal,
          close: close,
          warning: warning,
          success: success,
          closeByAlert: closeByAlert
      }
  })();

  module.exports = alertProvider;
